import { message } from 'antd';
import { parseAsync } from 'json2csv';

import request from '@/utils/request';

export const downLoad = (link) => {
  if (!link) {
    message.error('下载链接错误,请联系开发人员');
    return;
  }
  const elink = document.createElement('a');
  elink.style.display = 'none';
  elink.href = link;
  document.body.appendChild(elink);
  elink.click();
  document.body.removeChild(elink);
};

export const getDownLoadUrl = ({ path, ...params }) => {
  const search = new URLSearchParams(params).toString();
  return request(`${path}?${search}`).then((res) => {
    downLoad(res.download_url || res.data);
  });
};

export const exportCsv = ({ data, filename, costumTitles }) => {
  const rows = data;
  const fields = costumTitles ?? Object.keys(data[0]);
  parseAsync(rows, { fields: fields, excelStrings: true })
    .then((result) => {
      const link = document.createElement('a');
      link.href =
        'data:text/csv;charset=utf-8,\uFEFF' + encodeURIComponent(result);
      link.download = `${filename}.csv`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    })
    .catch((err) => {
      alert(err);
    });
};
